//
//  LoginMainController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/6.
//  Copyright © 2025 考拉🐨. All rights reserved.
//

import UIKit
import Localize_Swift
import JFPopup
import WebKit
import RealmSwift
import SwiftyUserDefaults
import SnapKit

enum LoginLanguage {
    /// 中文
    case chinese
    /// 俄语
    case russian
}

enum LoginType {
    /// 密码登录
    case password
    /// 验证码登录
    case code
}

private let totalSecond: Int = 60

class LoginMainController: BaseViewController {
    
    
    @IBOutlet weak var subtitleLabel: UILabel!
    
    /// 中文，俄语切换
    @IBOutlet weak var chinessView: UIView!
    @IBOutlet weak var russianView: UIView!
    @IBOutlet weak var chinessButton: UIButton!
    @IBOutlet weak var russianButton: UIButton!
    
    /// 请输入手机号
    @IBOutlet weak var mobileTextField: UITextField!
    
    
    /// 验证码标题
    @IBOutlet weak var codeView: UIView!
    @IBOutlet weak var codeTitleLabel: UILabel!
    @IBOutlet weak var codeTextField: UITextField!
    @IBOutlet weak var sendCodeButton: UIButton!
    
    /// 密码标题
    @IBOutlet weak var passwordView: UIView!
    @IBOutlet weak var passwordTitleLabel: UILabel!
    @IBOutlet weak var passwordTextField: UITextField!
    
    /// 登录
    @IBOutlet weak var loginButton: UIButton!
    
    /// 登录类型，密码登录、验证码登录
    @IBOutlet weak var loginTypeButton: UIButton!
    /// 忘记密码
    @IBOutlet weak var forgetButton: UIButton!
    
    /// 没有账号?
    @IBOutlet weak var noAccountLabel: UILabel!
    /// 立即注册
    @IBOutlet weak var registerButton1: UIButton!
    /// 协议内容
    @IBOutlet weak var agreementLabel: UILabel!
    @IBOutlet weak var userAgreementButton: UIButton!
    
    @IBOutlet weak var countryImageView: UIImageView!
    @IBOutlet weak var countryCodeLabel: UILabel!
    
    private var areaCodeModel: AreaCodeModel = AreaCodeModel.default
    
    private var language: LanguageTpye = .zh {
        didSet {
            // 保存语言
            LanguageManager.setLanguage(language)
            
            if language == .zh {
                chinessView.backgroundColor = .gradient(colors: [
                    UIColor(hex: "#64D4E3"),
                    UIColor(hex: "#2A8EFE")
                ], rect: CGRect(x: 0, y: 0, width: 78, height: 24))
                chinessView.addRoundedCorners(radius: 12, width: 1, color: .clear)
                chinessButton.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
                
                russianView.backgroundColor = .white
                russianView.addRoundedCorners(radius: 12, width: 1, color: UIColor(hex: "#8C8C8C"))
                russianButton.setTitleColor(UIColor(hex: "#8C8C8C"), for: .normal)
                
            } else {
                
                chinessView.backgroundColor = .white
                chinessView.addRoundedCorners(radius: 12, width: 1, color: UIColor(hex: "#8C8C8C"))
                chinessButton.setTitleColor(UIColor(hex: "#8C8C8C"), for: .normal)
                
                russianView.backgroundColor = .gradient(colors: [
                    UIColor(hex: "#64D4E3"),
                    UIColor(hex: "#2A8EFE")
                ], rect: CGRect(x: 0, y: 0, width: 116, height: 24))
                russianView.addRoundedCorners(radius: 12, width: 1, color: .clear)
                russianButton.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
            }
        }
    }
    
    private var loginType: LoginType = .password {
        didSet {
            passwordTextField.text = ""
            codeTextField.text = ""
            
            if loginType == .password {
                passwordView.isHidden = false
                codeView.isHidden = true
                loginTypeButton.setTitle("验证码登录".localized(.login), for: .normal)
                forgetButton.isHidden = false
                
            } else {
                passwordView.isHidden = true
                codeView.isHidden = false
                loginTypeButton.setTitle("账号登录".localized(.login), for: .normal)
                forgetButton.isHidden = true
            }
        }
    }
    
    private var timer: Timer?
    // true: 正在获取验证码, false: 发送已结束
    private var isSendingCode: Bool = false
    // true: 同意协议
    private var isAgree: Bool {
        userAgreementButton.isSelected
    }
    // 获取验证码倒计时秒数
    var second: Int = 0 {
        didSet {
            codeTextField.placeholder = "请输入短信验证码".localized(.login)
            if second >= totalSecond || second <= 0 {
                sendCodeButton.setTitle("获取验证码".localized(.login), for: .normal)
                
            } else {
                sendCodeButton.setTitle("\(second)s", for: .normal)
            }
        }
    }
    
    private lazy var areaCodeView: LoginAreaCodeView = {
        let areaCodeView = LoginAreaCodeView.loadFromNib()
        return areaCodeView
    }()
    
    // 强制更新
    private lazy var forcedUpdatingView = {
        let view = ForcedUpdatingView.loadFromNib()
        view.isHidden = true
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initNav()
        initUI()
        updateLanguageAction()
        
        language = .zh
        
        DispatchQueue.global().async {
            /// 异步线程
            let isNetworkConnect = UIDevice.isNetworkConnect
            xLog("网络 \(isNetworkConnect ? "已授权": "未授权")")
        }
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        language = LanguageManager.currentLanguage
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        initForcedUpdating()
        
    }
    
    /// 切换语言
    @IBAction  func changeLanguageAction(_ sender: UIButton) {
        language = sender.tag == 0 ? .zh: .ru
    }
    
    // 切换国家区号
    @IBAction func changeCountryAction(_ sender: UIButton) {
        // 复制分享内容
        areaCodeView.list = AreaCodeModel.dataSources()
        // 弹框
        popup.bottomSheet(enableDrag: false) {
            areaCodeView
        }
        
    }
    
    // 获取短信验证码
    @IBAction func getSMSAction(_ sender: Any) {
        getSMS()
    }
    
    // 勾选用户协议
    @IBAction func agreementAction(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        
    }
    
    // 登录
    @IBAction func loginAction(_ sender: UIButton) {
        view.endEditing(true)
        if mobileTextField.text!.isEmpty {
            YLHUD.showMessage("请输入手机号".localized(.login))
            return
        }
        
        if !String.checkMobile(id: areaCodeModel.id, mobile: mobileTextField.text!) {
            YLHUD.showMessage("请输入正确的手机号".localized(.login))
            return
        }
        
        if loginType == .password && passwordTextField.text!.isEmpty{
            // 账号登录，密码为空
            YLHUD.showMessage("请输入密码".localized(.login))
            return
        }
        
        if loginType == .code && codeTextField.text!.isEmpty{
            // 账号登录，密码为空
            YLHUD.showMessage("请输入短信验证码".localized(.login))
            return
        }
        
        if !isAgree {
            YLAlert(
                controller: self,
                title: "提示".localized(),
                message: "阅读并同意《GLUZ用户服务协议和隐私政策》".localized(.login),
                actionTitles: ["同意".localized()],
                cancelTitle: "拒绝".localized(),
                cancelStyle: .destructive
            ) { [self] action, index in
                userAgreementButton.isSelected = true
                if loginType == .password {
                    loginWithAccount()
                    
                } else {
                    loginWithCode()
                }
            }
            return
        }
        
        
        if loginType == .password {
            loginWithAccount()
            
        } else {
            loginWithCode()
        }
        
    }
    
    // 忘记密码
    @IBAction func forgetPasswordAction(_ sender: Any) {
        push(LoginForgetPasswordController())
    }
    
    // 切换登录方式
    @IBAction func changeLoginTypeAction(_ sender: UIButton) {
        loginType = (loginType == .code) ? .password: .code
    }
    
    /// 立即注册
    @IBAction func registerAction(_ sender: UIButton) {
        push(LoginRegisterController())
    }
    
    // 更新语言
    override func updateLanguageAction() {
        
        subtitleLabel.text = "跨越山海 链接未来".localized(.login)
        // chinessButton.setTitle("中文".localized(.login), for: .normal)
        chinessButton.setTitle("中文", for: .normal)
        russianButton.setTitle("RU".localized(.login), for: .normal)
        loginButton.setTitle("登 录".localized(.login), for: .normal)
        
        mobileTextField.placeholder = "请输入手机号".localized(.login)
        passwordTitleLabel.text = "密码".localized(.login)
        passwordTextField.placeholder = "请输入密码".localized(.login)
        codeTitleLabel.text = "验证码".localized(.login)
        codeTextField.placeholder = "请输入短信验证码".localized(.login)
        sendCodeButton.setTitle("获取验证码".localized(.login), for: .normal)
        
        forgetButton.setTitle("忘记密码".localized(.login), for: .normal)
        
        if loginType == .password {
            // 账号登录
            loginTypeButton.setTitle("验证码登录".localized(.login), for: .normal)
            
        } else {
            loginTypeButton.setTitle("账号登录".localized(.login), for: .normal)
        }
        
        noAccountLabel.text = "没有账号？".localized(.login)
        registerButton1.setTitle("立即注册".localized(.login), for: .normal)
        
        let text = NSMutableAttributedString(string: "阅读并同意《GLUZ用户服务协议和隐私政策》".localized(.login))
        text.color(UIColor(hex: "16C186"))
        text.color(UIColor(hex: "333333"), range: text.string.inRange(of: "阅读并同意".localized(.login)).first!)
        text.font(.systemFont(ofSize: 12))
        agreementLabel.attributedText = text
        
        view.layoutIfNeeded()
    }
    
    deinit {
        xLog("deinit -- \(self.className)")
        stopTimer()
    }
}

// MARK: - private
private extension LoginMainController {
    func initUI() {
        // 中文
        chinessView.backgroundColor = .gradient(colors: [
            UIColor(hex: "#64D4E3"),
            UIColor(hex: "#2A8EFE")
        ], rect: CGRect(x: 0, y: 0, width: 72, height: 24))
        chinessView.addRoundedCorners(radius: 12, width: 1, color: .clear)
        chinessButton.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        
        russianView.addRoundedCorners(radius: 12, width: 1, color: UIColor(hex: "#8C8C8C"))
        russianButton.setTitleColor(UIColor(hex: "#8C8C8C"), for: .normal)
        
        loginButton.backgroundColor = .gradient(colors: [
            UIColor(hex: "#278AFF"),
            UIColor(hex: "#66D6E2")
        ], rect: CGRect(x: 0, y: 0, width: xScreenW - 48, height: 48))
        loginButton.addRoundedCorners(radius: 24)
        
        userAgreementButton.touchExpand = 20
        agreementLabel.isUserInteractionEnabled = true
        agreementLabel.sg.addTapGesture(self, #selector(goToAgreementAction))
        
        loginType = .password
        loginTypeButton.isHidden = true
        
        areaCodeView.cancelBlock = {
            self.popup.dismissPopup()
        }
        
        areaCodeView.didSelectedBlock = { [self] model in
            countryImageView.image = model.image.toImage
            countryCodeLabel.text = "+" + model.code
            areaCodeModel = model
            popup.dismissPopup()
        }
        
#if DEBUG
        let chooseAccountBtn = UIButton(type: .custom)
        chooseAccountBtn.addTarget(self, action: #selector(chooseAccountBtnClick), for: .touchUpInside)
        chooseAccountBtn.setAttributedTitle(NSAttributedString(string: "选择账号", attributes: [
            .foregroundColor: UIColor.white,
            .font: UIFont.boldSystemFont(ofSize: 16)
        ]), for: .normal)
        chooseAccountBtn.setTitleColor(.white, for: .normal)
        chooseAccountBtn.backgroundColor = .gray
        chooseAccountBtn.addRoundedCorners(radius: 4, width: 1, color: ._0087_F_4)
        view.addSubview(chooseAccountBtn)
        chooseAccountBtn.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview().inset(16)
        }
        
        if let testAccount = TestAccountManager.shared.getAllSortTimeAccounts().first {
            mobileTextField.text = testAccount.username
            passwordTextField.text = testAccount.password
        }
        
#endif
    }
    
#if DEBUG
    @objc func chooseAccountBtnClick() {
        TestTool.showAccountPicker(from: self) { testAccount in
            self.mobileTextField.text = testAccount.username
            self.passwordTextField.text = testAccount.password
        }
    }
#endif
    
    func initNav() {
        // 返回按钮
        navigationItem.leftBarButtonItem = nil
        // 设置初始导航栏透明度
        vhl_navBarBackgroundAlpha = 0
    }
}

// MARK: - 响应事件
private extension LoginMainController {
    
    /// 获取验证码
    func getSMS() {
        
        if mobileTextField.text!.isEmpty {
            YLHUD.showMessage("请输入手机号".localized(.login))
            return
        }
        
        if !String.checkMobile(id: areaCodeModel.id, mobile: mobileTextField.text!) {
            YLHUD.showMessage("请输入正确的手机号".localized(.login))
            return
        }
        
        let target = LoginAPI.getSMS(areaCode: areaCodeModel.code, mobile: mobileTextField.text!, event: "mobilelogin", email: "111@qq.com")
        YLHUD.showLottie()
        YLRequest.request(target) { [self] result in
            switch result {
            case .success(let res):
                let dataDictionary = res.dataDictionary
                xLog(dataDictionary)
                let name = dataDictionary["name"] as? String
                let nameRu = dataDictionary["name_ru"] as? String
                
                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu))
                
                codeTextField.becomeFirstResponder()
                initTimer()
                
            case .failure(let err):
                let dataDictionary = err.dataDictionary
                xLog("dataDictionary \(dataDictionary as NSDictionary)")
                let name = dataDictionary["name"] as? String
                let nameRu = dataDictionary["name_ru"] as? String
                
                
                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu))
                
            }
        }
    }
    
    /// 账号登录
    func loginWithAccount() {
        
        let target = LoginAPI.loginAccount(country: areaCodeModel.id, account: mobileTextField.text, password: passwordTextField.text)
        YLHUD.showLottie()
        YLRequest.request(target) { result in
            switch result {
            case .success(let res):
                
#if DEBUG
                // 保存账号
                TestAccountManager.shared.handleLoginAutoSave(country: self.areaCodeModel.id, username: self.mobileTextField.text!, password: self.passwordTextField.text!)
#endif
                
                let dataDictionary = res.dataDictionary
                //                let name = dataDictionary["name"] as? String
                //                let nameRu = dataDictionary["name_ru"] as? String
                self.userInfo(dataDictionary: dataDictionary)
                
                //                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu)) {
                //                    if res.code == 1 {
                //                        self.userInfo(dataDictionary: dataDictionary)
                //                    }
                //                }
                
            case .failure(let err):
                let dataDictionary = err.dataDictionary
                xLog("dataDictionary \(dataDictionary as NSDictionary)")
                let name = dataDictionary["name"] as? String
                let nameRu = dataDictionary["name_ru"] as? String
                
                
                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu))
            }
        }
    }
    
    // 验证码登录
    func loginWithCode() {
        let target = LoginAPI.loginCode(captcha: codeTextField.text!, mobile: mobileTextField.text!, country: areaCodeModel.id)
        YLHUD.showLottie()
        YLRequest.request(target) { result in
            switch result {
            case .success(let res):
                let dataDictionary = res.dataDictionary
                self.userInfo(dataDictionary: dataDictionary)
                //                let name = dataDictionary["name"] as? String
                //                let nameRu = dataDictionary["name_ru"] as? String
                //
                //
                //                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu)) {
                //                    self.userInfo(dataDictionary: dataDictionary)
                //                }
                
                
            case .failure(let err):
                let dataDictionary = err.dataDictionary
                xLog("dataDictionary \(dataDictionary as NSDictionary)")
                let name = dataDictionary["name"] as? String
                let nameRu = dataDictionary["name_ru"] as? String
                
                
                YLHUD.showMessage(LanguageManager.currentLanguageToText(name, nameRu))
            }
        }
    }
    
    func userInfo(dataDictionary: [String: Any]) {
        
        UserProfile.token = dataDictionary["token"] as! String
        UserProfile.userId = dataDictionary["user_id"] as! Int
        UserProfile.mobile = dataDictionary["mobile"] as! String
        UserProfile.identityId = dataDictionary["identity_type"] as! Int
        UserProfile.avatar = dataDictionary["avatar"] as! String
        UserProfile.country = (dataDictionary["country"] ?? 0) as! Int
        UserProfile.username = (dataDictionary["username"] ?? "") as! String
        UserProfile.usernameRu = (dataDictionary["username_ru"] ?? "") as! String
        
        let userModel = UserModel()
        userModel.id = UserProfile.userId
        userModel.username = UserProfile.username
        userModel.usernameRu = UserProfile.usernameRu
        userModel.avatar = UserProfile.avatar
        userModel.country = UserProfile.country
        userModel.type = UserProfile.identityId
        // 保存用户个人信息
        RealmTools.add(userModel, update: .modified)
        
        // 更新即构的信息
        ZIMKitCore.shared.localUser?.id = String(userModel.id)
        ZIMKitCore.shared.localUser?.avatarUrl = userModel.avatar
        ZIMKitCore.shared.localUser?.name = userModel.username
        ZIMKitCore.shared.updateUserAvatarUrl(userModel.avatar)
        
        cleanCacheAndCookie()
        // LanguageManager.setLanguage(UserProfile.country)
        // xKeyWindow.rootViewController = BaseTabBarController()
        
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
            // 登录即构
            appDelegate.loginZego { data in
                DispatchQueue.main.async {
                    xLog("[ZEGO] 用户登录 \(data ?? [:])")
                    let code = (data?["code"] as? Int) ?? -1
                    xLog("[ZEGO] code \(code)")
                    if code == 0 {
                        YLHUD.showMessage("登录成功".localized()) {
                            LanguageManager.setLanguage(UserProfile.country)
                            if !(xKeyWindow.rootViewController is BaseTabBarController) {
                                xKeyWindow.rootViewController = BaseTabBarController()
                            }
                        }
                    } else {
                        // 登录失败
                        YLHUD.showMessage("登录失败".localized() + "(\(code))")
                        self.logout()
                    }
                }
            }
        }
        
    }
    
    // 退出登录
    func logout() {
        // IM 退出登录
        ZIMKit.disconnectUser()
        // 清空即构缓存的数据
        ZegoUIKit.shared.uninit()
        cleanCacheAndCookie()
        // 清空本地存储的数据
        UserProfile.clear()
    }
    
    
    func cleanCacheAndCookie() {
        xLog("清 webView 缓存")
        let dateSince1970 = Date(timeIntervalSince1970: 0) // 获取1970年以来的所有数据
        WKWebsiteDataStore.default().removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: dateSince1970) {
            // 清除完成后的回调
            // 如果你还需要清除与WKWebView相关的cookies，可以使用以下方法：
            HTTPCookieStorage.shared.removeCookies(since: Date(timeIntervalSince1970: 0))
            xLog("清除完成后的回调")
        }
    }
    
    // 强制更新
    func initForcedUpdating() {
        
        let target = LoginAPI.systemForcedUpdating
        YLRequest.request(target) { [self] result in
            switch result {
            case .success(let res):
                
                let dataDictionary = res.dataDictionary
                
                if let version = dataDictionary["version"] as? String {
                    // 需要强更
                    if Bundle.sg.appVersion.sg.compareVesion(to: version) == -1 {
                        forcedUpdatingView.isHidden = false
                        let content = dataDictionary["title"] as! String
                        let contentRu = dataDictionary["title_ru"] as! String
                        
                        forcedUpdatingView.versionLabel.text = version
                        forcedUpdatingView.updateContent = LanguageManager.isLanguageZH ? content: contentRu
                        view.addSubview(forcedUpdatingView)
                        view.bringSubviewToFront(forcedUpdatingView)
                    }
                }
                
            case .failure: break
            }
        }
    }
    
    // MARK: - 初始化定时器
    /// 初始化定时器
    func initTimer() {
        sendCodeButton.isEnabled = false
        second = totalSecond
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        if let curTimer: Timer = timer {
            RunLoop.main.add(curTimer, forMode: .common)
        }
        timer?.fire()
    }
    
    // 定时器action
    @objc func timerAction() {
        second = second - 1
        if second <= 0 {
            stopTimer()
            sendCodeButton.isEnabled = true
            codeTextField.placeholder = "请输入短信验证码".localized(.login)
            codeTextField.textContentType = .oneTimeCode
        }
    }
    
    // 停止定时
    func stopTimer() {
        if timer != nil {
            second = 0
            timer?.invalidate()
            timer = nil
        }
    }
    
    @objc func goToAgreementAction() {
        view.endEditing(true)
        push(BaseWebViewController(url: H5UrlManager.privacyUrl(type: "隐私政策"), displaysWebViewTitle: false, isNavBarHide: true))
    }
    
}
